package com.ikdong.toodle.service;

import com.ikdong.toodle.model.Account;
import com.ikdong.toodle.util.AccountManager;
import com.ikdong.toodle.util.AuthManager;
import com.ikdong.toodle.util.Constant;
import com.ikdong.toodle.util.ContextManager;
import com.ikdong.toodle.util.FolderManager;
import com.ikdong.toodle.util.GoalManager;
import com.ikdong.toodle.util.TaskManager;
import android.app.IntentService;
import android.content.Intent;
import android.util.Log;

public class SyncService extends IntentService {	
	public static final String ERROR_MESSAGE = "sync_error";
	
	public SyncService() {
		super(Constant.SERVICE_SYNC);
	}

	@Override	
	protected void onHandleIntent(Intent intent) {
		Log.d(Constant.TAG, "SyncService: begin sync....");
		boolean isFail = false;
		
		try {
			AuthManager aum = new AuthManager(this);
			aum.refreshKey();
			AccountManager am = new AccountManager(this);
			FolderManager fm = new FolderManager(this);	
			TaskManager tm = new TaskManager(this);
			ContextManager cm = new ContextManager(this);
			GoalManager gm = new GoalManager(this);
			
			Account oAccount = am.getAccountFromServer();
			Account lAccount = am.getAccount();
			
			//sync folders
			long localFolderTime = lAccount.getLastedit_folder()==null ? 0:lAccount.getLastedit_folder().longValue();
			long onlineFolderTime = oAccount.getLastedit_folder()==null ? 0:oAccount.getLastedit_folder().longValue();
			boolean isFolderEmpty = fm.get().size()==0;
			boolean isFolerSync = onlineFolderTime>localFolderTime || isFolderEmpty;
			fm.sync(isFolerSync);
			
			//sync contexts
			long localContextTime = lAccount.getLastedit_context()==null ? 0:lAccount.getLastedit_context().longValue();
			long onlineContextTime = oAccount.getLastedit_context()==null ? 0:oAccount.getLastedit_context().longValue();
			boolean isContextEmpty = cm.getContext().size()==0;
			boolean isContextSync = onlineContextTime>localContextTime || isContextEmpty;
			cm.sync(isContextSync);
			
			//sync goals
			long localGoalTime = lAccount.getLastedit_goal()==null ? 0:lAccount.getLastedit_goal().longValue();
			long onlineGoalTime = oAccount.getLastedit_goal()==null ? 0:oAccount.getLastedit_goal().longValue();
			boolean isGoalEmpty = gm.getGoal().size()==0;
			boolean isGoalSync = onlineGoalTime>localGoalTime || isGoalEmpty;
			gm.sync(isGoalSync);
			
			//sync tasks
			tm.sync();
			
			//save account
			am.save(oAccount);	
		} catch (Exception e) {
			isFail = true;
			Log.e(Constant.TAG, "SyncService",e);
		}
			
		sendDoneMessage(isFail);		
	}
	
	private void sendDoneMessage(boolean isFail){
		Log.d(Constant.TAG, "SyncService send message");
		Intent intent = new Intent(Constant.SERVICE_SYNC);
		intent.putExtra(ERROR_MESSAGE, isFail);
		
		sendBroadcast(intent);
	}
}
